﻿using System;
using System.Timers;
using Gfw.Infrastructure.Stock.Enums;
using Gfw.Infrastructure.Stock.Facilities;
using Gfw.Models.Stock;
using Gfw.Repositories.Stock;

namespace StockWcf.Manager
{
    public static class MarketManager
    {
        #region 涨价定时计数器
         static Timer upTimer;
         static void Start()
        {
            if (upTimer == null)
            {
                upTimer = new Timer()
                              {
                                  AutoReset = true,
                                  Enabled = false,
                                  Interval = 1000 * 60
                              };

                upTimer.Elapsed += new ElapsedEventHandler(upTimer_Elapsed);
            }
            upTimer.Start();
        }
         static void Stop()
        {
            if (upTimer == null)
                return;
            if (upTimer.Enabled)
            {
                upTimer.Stop();
                upTimer.Close();
            }
            upTimer = null;
        }

        /// <summary>
        /// 开始计时
        /// </summary>
        public static void UpPriceStart()
        {
            //游戏处于正常交易手段
            if (Market.RunningState == (int)MarketRunningStateEnum.Normal)
            {
                Start();
            }
        }

        public static void UpPriceStop()
        {
            Stop();

        }

        static void upTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _UpPrice();
        }
        #endregion

        #region 价格维护

        private const decimal UpUnit = 0.0001M;
        private static MarketRepository marketRepository = new MarketRepository();
        private static StkMarket market;

        public static StkMarket Market
        {
            get { return market ?? (market = marketRepository.Unique()); }
        }

        private static void _UpPrice()
        {
            if (Market.RunningState == (int)MarketRunningStateEnum.Normal)
            {
                try
                {
                    Market.CurrentPrice += UpUnit;
                    marketRepository.Update(Market);
                }
                catch(Exception exp)
                {
                    //出现异常，返回
                    return;
                }
                //如果涨价成功，现在开始完成自动卖出股票
                lock (TradeManager.excuteLock)
                {
                    AutoSellManager.AutoSell(Market.CurrentPrice);
                    //不管有没有股票的自动卖出，都应该调用交易执行按钮
                    TradeManager.Execute();
                }
            }

        }

        #endregion

       

        #region 股票游戏状态维护
        /// <summary>
        /// 更改游戏状态
        /// </summary>
        /// <param name="stateEnum"></param>
        internal static void ChageMarketState(MarketRunningStateEnum stateEnum)
        {
            Market.RunningState = (int)stateEnum;
            marketRepository.Update(Market);
        }

        #endregion

        //#region 股票趋势维护 成交量，成交价格
        //static Timer tendencyTimer;
        //static void TendencyStart()
        //{
        //    if (tendencyTimer == null)
        //    {
        //        tendencyTimer = new Timer()
        //        {
        //            AutoReset = true,
        //            Enabled = false,
        //            Interval = 1000 * 60 * 5
        //        };

        //        tendencyTimer.Elapsed += new ElapsedEventHandler(tendencyTimer_Elapsed);

        //        DayTendency();
        //    }
        //      tendencyTimer.Start();
           
        //}
        //static void TendencyStop()
        //{
        //    if (tendencyTimer == null)
        //        return;
        //    if (tendencyTimer.Enabled)
        //    {
        //        tendencyTimer.Stop();
        //        tendencyTimer.Close();
        //    }
        //    tendencyTimer = null;
        //}

        //static void tendencyTimer_Elapsed(object sender, ElapsedEventArgs e)
        //{
        //    DayTendency();
        //}

        //static void DayTendency()
        //{
        //    BargainRecordRepository rep = new BargainRecordRepository();
        //    var count = rep.TendencyCountByDay(DateTime.Today);
        //    MarketTrendFacility facility = new MarketTrendFacility(TendencyTypeEnum.D1, Market.CurrentPrice, count, DateTime.Today);
        //    facility.Execute();
        //}

        //public static void TendencyRun()
        //{
        //    TendencyStart();
        //}
        //#endregion

        #region 股票游戏运行状态
        public static void MarketServiceStart()
        {
            var rep =new RunstatusRepository();
            var status = new StkRunstatus()
                             {
                                 Id = Guid.NewGuid().ToString(),
                                 UserId = "system",
                                 OperationType = 1,
                                 OperationDate = DateTime.Now,
                                 Description = "启动服务"
                             };
            rep.Save(status);
        }

        public static void MarketServiceStop()
        {
            var rep = new RunstatusRepository();
            var status = new StkRunstatus()
            {
                Id = Guid.NewGuid().ToString(),
                UserId = "system",
                OperationType = 0,
                OperationDate = DateTime.Now,
                Description = "停止服务"
            };
            rep.Save(status);
        }
        #endregion
    }
}
